local skel = fk.CreateSkill {
  name = "rmt__migui",
  dynamic_desc = function (self, player, lang)
    if #player:getTableMark("rmt__migui_used") > 3 then
      return "rmt__migui_dyn"
    end
  end,
}

--- 获取可以选择的花色或颜色
---@param player Player
local getMiguiChoices = function (player)
  local used = player:getTableMark("rmt__migui_used")
  local color = #used > 3
  local choices = color and  {"red", "black"} or {"log_spade", "log_heart", "log_diamond", "log_club"}
  if color and player:hasSkill("rmt__shengtong") then
    table.insert(choices, "nocolor")
  end
  return table.filter(choices, function(c) return not table.contains(used, c) end)
end

-- 更新目标角色的显示标记
---@param player ServerPlayer
local function updataMiguiMark(player)
  local room = player.room
  local suits, colors = {}, {}
  for _, p in ipairs(room.alive_players) do
    for _, v in ipairs(p:getTableMark("rmt__migui_record")) do
      if v[1] == player.id then
        local choice = v[2]
        if choice:startsWith("log_") then
          table.insert(suits, choice)
        else
          table.insert(colors, choice)
        end
      end
    end
  end
  room:setPlayerMark(player, "@rmt__migui_suit", #suits > 0 and suits or 0)
  local map = {["red"] = '<font color="#CC3131">红</font>', ["nocolor"] = '<font color="grey">无</font>', ["black"] = "黑"}
  room:setPlayerMark(player, "@rmt__migui_color", #colors > 0 and table.map(colors, function(c) return map[c] or c end) or 0)
end

-- 死亡后把目标脸上的标记也消除
skel:addLoseEffect(function (self, player, is_death)
  player.room:setPlayerMark(player, "rmt__migui_used", 0)
    local record = player:getTableMark("rmt__migui_record")
    if #record == 0 then return end
    local tos = {}
    for i = #record, 1, -1 do
      local v = record[i]
      table.insertIfNeed(tos, v[1])
    end
    if #tos == 0 then return end
    player.room:setPlayerMark(player, "rmt__migui_record", 0)
    for _, pid in ipairs(tos) do
      updataMiguiMark(player.room:getPlayerById(pid))
    end
end)

skel:addEffect("active", {
  name = "rmt__migui",
  anim_type = "offensive",
  card_num = 0,
  target_num = 1,
  card_filter = Util.FalseFunc,
  prompt = function (self, player, selected_cards, selected_targets)
    local choice = self.interaction.data
    if type(choice) == "string" then
      return "#rmt__migui:::"..choice
    end
    return " "
  end,
  interaction = function(self, player)
    return UI.ComboBox { choices = getMiguiChoices(player) }
  end,
  target_filter = function (self, player, to_select, selected)
    return #selected == 0
  end,
  can_use = function(self, player)
    return #getMiguiChoices(player) > 0
  end,
  on_use = function(self, room, effect)
    local player = effect.from
    local to = effect.tos[1]
    local choice = self.interaction.data
    room:addTableMark(player, "rmt__migui_used", choice) -- 已发动的选项
    room:addTableMark(player, "rmt__migui_record", {to.id, choice}) -- 选择的目标和对应花色选择
    updataMiguiMark(to)
  end,
})

skel:addEffect(fk.CardUsing, {
  is_delay_effect = true,
  anim_type = "control",
  can_trigger = function (self, event, target, player, data)
    if target == player and not player.dead and (data.card.type == Card.TypeBasic or data.card:isCommonTrick()) then
      local color, suit = data.card:getColorString(), data.card:getSuitString(true)
      local record = player:getMark("rmt__migui_record")
      if record == 0 then return false end
      local toId, icon
      for _, v in ipairs(record) do
        if v[2] == color or v[2] == suit then
          toId = v[1]
          icon = v[2]
          break
        end
      end
      if toId then
        local to = player.room:getPlayerById(toId)
        if not to.dead and table.contains(data:getExtraTargets({bypass_times = true, bypass_distances = true}), to) then
          event:setCostData(self, {tos = {to}, icon = icon})
          return true
        end
      end
    end
  end,
  on_cost = function (self, event, target, player, data)
    local to = event:getCostData(self).tos[1]
    return player.room:askToSkillInvoke(player, {
      skill_name = skel.name, prompt = "#rmt__migui-extra:"..  (to.id).."::"..data.card:toLogString()
    })
  end,
  on_use = function (self, event, target, player, data)
    local to = event:getCostData(self).tos[1]
    data:addTarget(to)
  end,
})

--- 每回合结束时，清理花色标记
skel:addEffect(fk.TurnEnd, {
  late_refresh = true,
  can_refresh = function (self, event, target, player, data)
    return player:getMark("rmt__migui_record") ~= 0
  end,
  on_refresh = function (self, event, target, player, data)
    local tos = {}
    local record = player:getMark("rmt__migui_record")
    if #record == 0 then return end
    for i = #record, 1, -1 do
      local v = record[i]
      if v[2]:startsWith("log_") then
        table.insertIfNeed(tos, v[1])
        table.remove(record, i)
      end
    end
    if #tos == 0 then return end
    player.room:setPlayerMark(player, "rmt__migui_record", #record > 0 and record or 0)
    for _, pid in ipairs(tos) do
      updataMiguiMark(player.room:getPlayerById(pid))
    end
  end,
})

Fk:loadTranslationTable{
  ["rmt__migui"] = "觅轨",
  [":rmt__migui"] = "每种花色限一次，出牌阶段，你可为之选择一名角色，本回合你使用此花色的基本牌或普通锦囊牌可额外指定其为目标。每种花色均选择后，将花色改为颜色，本回合改为本局。",
  [":rmt__migui_dyn"] = "每种颜色限一次，出牌阶段，你可为之指定一名角色，本局你使用此颜色的基本牌或普通锦囊牌可额外指定其为目标。",

  ["#rmt__migui"] = "觅轨：指定一名角色，你使用【%arg】牌可额外指定其为目标",
  ["@rmt__migui_suit"] = "觅轨",
  ["@rmt__migui_color"] = "觅轨",
  ["#rmt__migui_delay"] = "觅轨",
  ["#rmt__migui-extra"] = "觅轨：你可以将 %src 额外指定为 %arg 的目标",

  ["$rmt__migui1"] = "",
  ["$rmt__migui2"] = "",
}

return skel
